import requests
import os

def download_audio(url, save_path):
    """
    下载音频文件
    :param url: 音频文件的下载链接
    :param save_path: 音频文件的保存路径
    """
    try:
        # 发送请求获取音频内容
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 确保保存目录存在
        save_dir = os.path.dirname(save_path)
        if save_dir and not os.path.exists(save_dir):
            os.makedirs(save_dir)

        # 写入文件
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)
        print(f"音频文件已成功下载到 {save_path}")
    except requests.RequestException as e:
        print(f"下载失败: {e}")
    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    # 替换为实际的音频下载链接
    audio_url = "https://example.com/sample_audio.mp3"
    # 替换为实际要保存的文件名，可自定义路径
    save_file_path = "audio/sample_audio.mp3"
    download_audio(audio_url, save_file_path)
